package com.szz.cardecision.service;

import com.szz.cardecision.entity.Consultation;
import com.szz.cardecision.entity.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

@Component
public class DeepSeekLLMProvider implements LLMProvider {
    private final HttpClient httpClient = HttpClient.newHttpClient();
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Value("${deepseek.api-key:${deepseek.api.key:${deepseek.key:}}}")
    private String apiKeyProp;

    @Override
    public String name() { return "DeepSeek"; }

    @Override
    public String generateAdvice(User user, Consultation c) {
        String apiKey = (apiKeyProp != null && !apiKeyProp.isBlank()) ? apiKeyProp : System.getenv("DEEPSEEK_API_KEY");
        String prompt = buildPrompt(user, c);
        if (apiKey == null || apiKey.isBlank()) {
            return "[DeepSeek] 未配置 API Key，返回演示建议：\n" + demoAdvice(prompt);
        }

        try {
            // Build JSON via Jackson to properly escape newlines and characters
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("model", "deepseek-chat");
            bodyMap.put("messages", List.of(Map.of("role", "user", "content", prompt)));
            String bodyJson = objectMapper.writeValueAsString(bodyMap);

            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://api.deepseek.com/v1/chat/completions"))
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(bodyJson, StandardCharsets.UTF_8))
                    .build();

            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() >= 200 && response.statusCode() < 300) {
                return "[DeepSeek] " + Optional.ofNullable(response.body()).orElse("(empty)");
            } else {
                return "[DeepSeek] 调用失败: HTTP " + response.statusCode() + "\n" + response.body();
            }
        } catch (Exception ex) {
            return "[DeepSeek] 异常: " + ex.getMessage();
        }
    }

    private String buildPrompt(User user, Consultation c) {
        StringBuilder sb = new StringBuilder();
        sb.append("你是资深汽车顾问。请基于以下信息提供购车建议，包含：推荐车型、理由、预算匹配、优缺点与注意事项。\n");
        sb.append("用户偏好：预算").append(user.getBudgetMin()).append("-").append(user.getBudgetMax())
                .append(", 车型:").append(nullToEmpty(user.getPreferredBodyType())).append("\n");
        sb.append("咨询需求：预算").append(c.getBudgetMin()).append("-").append(c.getBudgetMax())
                .append(", 类型:").append(nullToEmpty(c.getBodyType()))
                .append(", 场景:").append(nullToEmpty(c.getScenes()))
                .append(", 能源:").append(nullToEmpty(c.getFuelType()))
                .append(", 品牌偏好:").append(nullToEmpty(c.getBrandPreference())).append("\n");
        sb.append("请结构化输出：1) 推荐车型列表 2) 对比分析 3) 预算建议 4) 购车注意事项\n");
        return sb.toString();
    }

    private String nullToEmpty(String s) { return s == null ? "" : s; }
    private String demoAdvice(String prompt) {
        return "基于提示：\n" + prompt + "\n- 推荐：插混SUV与经济型轿车\n- 对比：续航/空间/保养成本\n- 预算：建议预留购置税与保险\n- 注意：试驾关注底盘与NVH";
    }
}